from fastapi import Request, FastAPI
from fastapi.responses import JSONResponse

from app_v2.AsyncDataBase import AsyncDBError
from app_v2.db import DBError


class CookieError(Exception):
    pass


async def cookie_error_handler(_request: Request, _exc: Exception):
    return JSONResponse(
        status_code=200,
        content={"code": 444, "message": "cookie outdated"}
    )


async def key_error_exception_handler(_request: Request, exc: Exception):
    print(exc)
    return JSONResponse(
        status_code=200,
        content={"code": 444, "message": "api error because of outdated cookie"})


async def db_error_exception_handler(_request: Request, exc: Exception):
    print(exc)
    return JSONResponse(
        status_code=500,
        content={
            "code": 500,
            "message": "db error"
        })


async def exception_handler(_request: Request, exc: Exception):
    print(exc)
    return JSONResponse(
        status_code=500,
        content={
            "code": 500,
            "message": "internal server error"
        })


def init_error_handlers(app: FastAPI):
    app.add_exception_handler(KeyError, key_error_exception_handler)
    app.add_exception_handler(DBError, db_error_exception_handler)
    app.add_exception_handler(AsyncDBError, db_error_exception_handler)
    app.add_exception_handler(CookieError, cookie_error_handler)
    app.add_exception_handler(Exception, exception_handler)
